<template>
  <div class="rule-container">
    <el-dialog
      :visible.sync="dialog"
      :close-on-click-modal="false"
      :title="ruleDialogTitle"
      width="850px"
      top="1"
      @close="doClose"
    >
      <el-container>
        <div style="padding-top:0px;width:100%;">
          <el-divider content-position="center">规则
            <template v-if="showId"><span>【{{ id }}】</span></template>
          </el-divider>
          <el-form ref="ruleForm" :model="rule" :rules="rules" :inline="true" size="mini" label-position="right" label-width="100px">
            <el-row>
              <el-col :span="12">
                <el-form-item label="规则业务类:" required prop="businessTypeIds">
                  <el-select v-model="rule.businessTypeIds" placeholder="可以多选" multiple style="width: 180px;" size="mini">
                    <el-option v-for="item in parent.ruleApplyTypes" :key="item.value" style="line-height: 20px;height:25px;" :label="item.name" :value="item.value" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="表单名称:" required prop="sheetVariableName">
                  <el-select v-model="rule.sheetVariableName" placeholder="请选择" style="width: 180px;" size="mini">
                    <el-option v-for="item in parent.sheetNames" :key="item.value" style="line-height: 20px;height:25px;" :label="item.name" :value="item.value" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="Excel列号:" required prop="columnIndex">
                  <el-input v-model="rule.columnIndex" placeholder="点击按钮选择" disabled style="width: 180px;" size="mini" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="Excel列名:" required prop="columnName">
                  <el-input v-model="rule.columnName" placeholder="点击按钮选择" disabled style="width: 180px;" size="mini" />
                  <el-button size="mini" type="primary" round @click="selectSheetColumn">选择表单列</el-button>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="生效日期:" required prop="effectiveDate">
                  <el-date-picker v-model="rule.effectiveDate" type="date" format="MM/dd/yyyy" style="width: 180px;" placeholder="选择日期" size="mini" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="失效日期:" required prop="expirationDate">
                  <el-date-picker v-model="rule.expirationDate" type="date" format="MM/dd/yyyy" style="width: 180px;" placeholder="选择日期" size="mini" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="规则描述:">
                  <el-input v-model="rule.ruleDescription" type="textarea" :rows="1" placeholder="请输入内容" style="width: 180px;" clearable size="mini" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="二次校验:" required prop="secondCheck">
                  <el-radio-group v-model="rule.secondCheck" size="mini">
                    <el-radio v-for="secondCheck in secondChecks" :key="secondCheck.value" :label="secondCheck.value">{{ secondCheck.name }}</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>

          <!-- 操作 -->
          <action ref="action" :action="action" />
          <!-- 条件 -->
          <condition v-for="(condition,index) in conditions" :key="index" :index="index" :condition="condition" :condition-size="conditions.length" :parent="currentObject" @delCondition="delCondition" @addCondition="addCondition" />
        </div>
      </el-container>
      <el-row :gutter="20">
        <el-col :span="12"><div style="padding-top:5px;text-align:right;"><el-button type="primary" size="small" round @click="doSave()">保存</el-button></div></el-col>
        <el-col :span="12"><div style="padding-top:5px"><el-button type="primary" size="small" round @click="doClose()">取消</el-button></div></el-col>
      </el-row>
      <sheetColumnList ref="sheetColumnList" :parent="parent" @setSheetColumn="setSheetColumn" />
    </el-dialog>
  </div>
</template>

<script>
import condition from './condition'
import action from './action'
import { addOrUpdateRule3 } from '@/api/rule3'
import { findRule3 } from '@/api/rule3'
import { Message } from 'element-ui'
import sheetColumnList from './sheetColumnList'

export default {
  components: {
    condition,
    action,
    sheetColumnList
  },
  props: {
    parent: {
      type: Object,
      default: null
    },
    ruleDialogTitle: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      currentObject: this,
      dialog: false,
      conditions: [this.getEmptyCondition()],
      action: this.getEmptyAction(),
      rule: this.getEmptyRule3(),
      rules: {
        columnIndex: [{ required: true, message: '列号不能为空', trigger: 'blur' }, { required: true, message: '列号不能为空', trigger: 'change' }],
        columnName: [{ required: true, message: '列名不能为空', trigger: 'blur' }, { required: true, message: '列名不能为空', trigger: 'change' }],
        businessTypeIds: [{ required: true, message: '规则业务类不能为空', trigger: 'blur' }, { required: true, message: '规则业务类不能为空', trigger: 'change' }],
        sheetVariableName: [{ required: true, message: '表单名称不能为空', trigger: 'blur' }, { required: true, message: '表单名称不能为空', trigger: 'change' }],
        effectiveDate: [{ required: true, message: '生效日期不能为空', trigger: 'blur' }, { required: true, message: '生效日期不能为空', trigger: 'change' }],
        expirationDate: [{ required: true, message: '失效日期不能为空', trigger: 'blur' }, { required: true, message: '失效日期不能为空', trigger: 'change' }],
        secondCheck: [{ required: true, message: '二次校验选项不能为空', trigger: 'blur' }, { required: true, message: '二次校验选项不能为空', trigger: 'change' }]
      },
      sheetNames: [{ name: '', value: null }],
      within: 'within',
      external: 'external',
      between: 'between',
      length: 'length',
      id: '',
      secondChecks: [{ name: '启用', value: 1 }, { name: '禁用', value: 0 }]
    }
  },
  computed: {
    showId: function() {
      return this.id !== null && this.id !== ''
    },
    secondValidate: {
      set: function(val) {
        this.rule.secondValidate = val
      },
      get: function() {
        return (this.rule.secondValidate === null || this.rule.secondValidate === '') ? 'Y' : this.rule.secondValidate
      }
    }
  },
  methods: {
    selectSheetColumn() {
      if (this.rule.sheetVariableName === null || this.rule.sheetVariableName === '') {
        this.$confirm('请选择表单名称！', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
        })
        return
      }
      const _sheetColumnList = this.$refs.sheetColumnList
      _sheetColumnList.sheetColumnDialogTitle = '表单列名选择'
      _sheetColumnList.dialog = true
      _sheetColumnList.callbackMethod = 'setSheetColumn'
      _sheetColumnList.sheetVariableName = this.rule.sheetVariableName
    },
    setSheetColumn(val) {
      if (!val) {
        this.rule.columnName = ''
        return
      }
      this.rule.columnIndex = val.columnIndex
      this.rule.columnName = val.columnName
    },
    // 添加条件
    addCondition: function() {
      var condition = this.getEmptyCondition()
      this.conditions.push(condition)
    },
    // 删除条件
    delCondition: function(index) {
      if (this.conditions.length <= 1) {
        return
      }
      this.$confirm('是否删除条件' + (index + 1) + '?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.conditions.splice(index, 1)
      })
    },
    // 关闭
    doClose: function() {
      this.dialog = false
      this.reset()
    },
    // 保存
    doSave: function() {
      var _this = this

      // 判断条件是否为空
      this.$confirm('是否保存信息?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (this.conditions.length <= 0) {
          this.$confirm('规则条件不能为空!', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
          return
        }

        // 校验表单
        var _valid = true
        _this.$refs.ruleForm.validate(valid => {
          _valid = valid
        })
        if (!_valid) {
          return
        }

        // 检查规则条件
        for (var i = 0; i < this.conditions.length; i++) {
          if (!this.validateCondition(i)) {
            return
          }
        }

        this.resetConditions()

        // 检查操作
        if (!this.validateAction()) {
          return
        }

        this.rule.conditions = this.conditions
        this.rule.action = this.action

        addOrUpdateRule3(this.rule).then(res => {
          Message({
            message: res.result,
            type: 'success',
            duration: 2 * 1000
          })
          this.dialog = false
          this.reset()
          this.parent.toQuery()
        })
      })
    }, // 重置条件
    resetConditions() {
      if (this.conditions === null || this.conditions.length <= 0) {
        return
      }
      for (var i = 0; i < this.conditions.length; i++) {
        var condition = this.getEmptyCondition()
        condition.ruleId = this.conditions[i].ruleId
        condition.columnIndex = this.conditions[i].columnIndex
        condition.columnName = this.conditions[i].columnName
        condition.sheetVariableName = this.conditions[i].sheetVariableName
        condition.operation = this.conditions[i].operation
        condition.conditionType = this.conditions[i].conditionType
        condition.withinIgnoreCase = this.conditions[i].withinIgnoreCase
        condition.betweenIgnoreCase = this.conditions[i].betweenIgnoreCase
        condition.minLength = this.conditions[i].minLength
        condition.maxLength = this.conditions[i].maxLength

        if (this.conditions[i].conditionType === this.within) {
          condition.colWithinJudgeType = this.conditions[i].colWithinJudgeType
          condition.colWithinJudgeValue = this.conditions[i].colWithinJudgeValue
        } else if (this.conditions[i].conditionType === this.external) {
          condition.colExternalJudgeType = this.conditions[i].colExternalJudgeType
          condition.colExternalJudgeValue = this.conditions[i].colExternalJudgeValue
        } else if (this.conditions[i].conditionType === this.between) {
          condition.sheetVariableName2 = this.conditions[i].sheetVariableName2
          condition.columnIndex2 = this.conditions[i].columnIndex2
          condition.columnName2 = this.conditions[i].columnName2
          condition.operation2 = this.conditions[i].operation2
        }
        this.conditions[i] = condition
      }
    }, // 重置
    reset() {
      this.conditions.splice(0, this.conditions.length)
      this.conditions.push(this.getEmptyCondition())
      this.action = this.getEmptyAction()
      this.rule = this.getEmptyRule3()
      this.rule.conditions = this.conditions
      this.rule.action = this.action
      this.id = ''
    },
    // 获取规则3信息
    getRule3(ruleId) {
      var _this = this
      this.rule.ruleId = ruleId
      findRule3(ruleId).then(res => {
        _this.rule = res.result
        _this.action = res.result.action
        _this.conditions = res.result.conditions
        if (_this.conditions === null || _this.conditions.length <= 0) {
          _this.conditions.push(_this.getEmptyCondition())
        }
      })
    },
    // 条件空对象
    getEmptyCondition: function() {
      return {
        ruleId: null,
        sheetVariableName: null,
        columnIndex: null,
        columnName: null,
        conditionType: null,
        colWithinJudgeType: null,
        colWithinJudgeValue: null,
        colExternalJudgeType: null,
        colExternalJudgeValue: null,
        operation: null,
        columnIndex2: null,
        columnName2: null,
        operation2: null,
        sheetVariableName2: null,
        withinIgnoreCase: null, // 忽略大小写
        betweenIgnoreCase: null, // 忽略大小写
        maxLength: null,
        minLength: null
      }
    },
    // 操作空对象
    getEmptyAction() {
      return { ruleId: null, overwrite: null, frontAppend: null, backAppend: null, message: null, allowedSubmit: 'N', replacementOld: null, replacementNew: null }
    },
    // 获取空规则3
    getEmptyRule3() {
      return {
        ruleId: null,
        sheetVariableName: null,
        columnIndex: null,
        columnName: null,
        applyType: null,
        businnessTypeIds: null,
        ruleDescription: null,
        effectiveDate: new Date(),
        expirationDate: '2049-12-30',
        conditions: this.conditions,
        action: this.action,
        secondCheck: 0 // 默认禁用二次校验
      }
    },
    validateCondition(index) {
      // 验证条件是否已经填写.
      if ((this.conditions[index].columnIndex === null || this.conditions[index].columnIndex === '')) {
        this.$confirm('规则【条件' + (index + 1) + '】列号不能为空!', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        return false
      }
      if ((this.conditions[index].columnName === null || this.conditions[index].columnName === '')) {
        this.$confirm('规则【条件' + (index + 1) + '】列号不能为空!', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        return false
      }
      if ((this.conditions[index].sheetVariableName === null || this.conditions[index].sheetVariableName === '')) {
        this.$confirm('规则【条件' + (index + 1) + '】表单名称不能为空!', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        return false
      }

      if (this.conditions[index].conditionType === null || this.conditions[index].conditionType === '') {
        this.$confirm('规则【条件' + (index + 1) + '】请选择条件类型!', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        return false
      }
      // 列内值判断
      if (this.conditions[index].conditionType === this.within && (this.conditions[index].colWithinJudgeType === null || this.conditions[index].colWithinJudgeType === '')) {
        this.$confirm('条件' + (index + 1) + ' 请选择列内判断类型!', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        return false
      }
      if (this.conditions[index].conditionType === this.within && (this.conditions[index].colWithinJudgeValue === null || this.conditions[index].colWithinJudgeValue === '')) {
        this.$confirm('条件' + (index + 1) + ' 列内判断条件值不能为空!', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        return false
      }

      // 外部条件判断
      if (this.conditions[index].conditionType === this.external && (this.conditions[index].colExternalJudgeType === null || this.conditions[index].colExternalJudgeType === '')) {
        this.$confirm('条件' + (index + 1) + '请选择外联判断类型!', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        return false
      }
      if (this.conditions[index].conditionType === this.external && (this.conditions[index].colExternalJudgeValue === null || this.conditions[index].colExternalJudgeValue === '')) {
        this.$confirm('条件' + (index + 1) + '外联判断条件值不能为空!', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        return false
      }

      // 与其他列比较判断
      if (this.conditions[index].conditionType === this.between && (this.conditions[index].columnIndex2 === null || this.conditions[index].columnIndex2 === '')) {
        this.$confirm('条件' + (index + 1) + '列间判断的【列号】不能为空!', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        return false
      }
      if (this.conditions[index].conditionType === this.between && (this.conditions[index].columnName2 === null || this.conditions[index].columnName2 === '')) {
        this.$confirm('条件' + (index + 1) + '列间判断的【列名】不能为空!', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        return false
      }
      if (this.conditions[index].conditionType === this.between && (this.conditions[index].operation2 === null || this.conditions[index].operation2 === '')) {
        this.$confirm('条件' + (index + 1) + '列间判断的【关系】不能为空!', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        return false
      }
      if (this.conditions[index].conditionType === this.between && (this.conditions[index].sheetVariableName2 === null || this.conditions[index].sheetVariableName2 === '')) {
        this.$confirm('条件' + (index + 1) + '列间判断的【表单名称】不能为空!', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        return false
      }

      if (this.conditions[index].conditionType === this.length) {
        if (this.conditions[index].minLength !== null &&
          this.conditions[index].maxLength !== null &&
          this.conditions[index].minLength > this.conditions[index].maxLength) {
          this.$confirm('条件' + (index + 1) + '长度判断：“最小长度”不能大于“最大长度”', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
          return false
        }
      }

      if (this.showOperation(index) && (this.conditions[index].operation === null || this.conditions[index].operation === '')) {
        this.$confirm('与条件' + (index + 2) + '的【关系】不能为空!!', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        return false
      }
      return true
    },
    validateAction() {
      if ((this.action.overwrite === null || this.action.overwrite === '') &&
        (this.action.frontAppend === null || this.action.frontAppend === '') &&
        (this.action.backAppend === null || this.action.backAppend === '') &&
        (this.action.replacementOld === null || this.action.replacementOld === '') &&
        (this.action.replacementNew === null || this.action.replacementNew === '') &&
        (this.action.message === null || this.action.message === '')) {
        this.$confirm('规则【操作】不能为空!', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        return false
      }
      return true
    },
    // 最后一个条件表达式不显示操作符
    showOperation: function(index) {
      var size = this.conditions.length - 1
      if (size === index) {
        return false
      } else {
        return true
      }
    }
  }
}
</script>
<style scoped>
  .el-row {
    margin-bottom: 5px;
  }
  .el-col {
    border-radius: 4px;
  }
  .bg-purple-dark {
    background: #99a9bf;
  }
  .bg-purple {
    background: #d3dce6;
  }
  .bg-purple-light {
    background: #e5e9f2;
  }
  .grid-content {
    border-radius: 4px;
    min-height: 36px;
  }
  .row-bg {
    padding: 10px 0;
    background-color: #f9fafc;
  }
  .rule-container .el-form-item--small.el-form-item {
    margin-bottom: 13px
  }
  .rule-container .el-form-item--mini.el-form-item {
    margin-bottom: 13px
  }
  .rule-container >>> .el-divider.el-divider--horizontal{
    margin: 10px 10;
  }
  .rule-container >>> .el-dialog__body {
    padding: 0px 20px 1px 20px;
  }
  /*.el-form-item--mini.el-form-item {
    margin: 0px 0px 0px 0px;
    padding: 0px 0px 0px 0px;
  }**/
</style>
